from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
import json
import datetime
import numpy as np
import pandas as pd
import requests
import re
import csv
'''
功能：访问API获取天气
参数：
返回值：
崩了，抛弃
'''
def weather():
    rep = requests.get('http://www.tianqiapi.com/api?version=v6&appid=23035354&appsecret=8YvlPNrz&city=北京')
    rep.encoding = 'utf-8'

    # if rep.json()['errcode']==100:
    return '',''
    #else:
    #   return rep.json()['wea'],rep.json()['date']


'''
功能：调用爬虫，爬取（更新）新闻
参数：
返回值：返回新闻标题、新闻url
'''
def getnews(category):
    time = datetime.datetime.now()
    newslist = []
    for i in range(5):
        filepath = "../OlpApp/static/data/News" + str(i) + str(time).split(' ')[0] + ".csv"
        df = pd.read_csv(filepath, encoding='utf-8', names=["title", "link"])
        print(df)
        title = df['title'].tolist()
        link = df['link'].tolist()
        news = []
        for t, l in zip(title, link):
            news.append([t, l])
        newslist.append(news)
    return newslist[int(category)]

'''
功能：计算总分
参数：
返回值：总分
'''
def data_on_map():
    df = pd.read_csv('static/data/medalList.csv', encoding='gbk')
    medals_2020 = np.array(df)
    score=[]
    for item in medals_2020:
        if item[1]=='俄罗斯奥运队':
            item[1]='俄罗斯'
        score.append({'name':str(item[1]),'value':int(item[2]+item[3]+item[4])})
    return score


'''
功能：获取2020年奖牌榜前十的奖牌情况
参数：
返回值：2020年奖牌榜前十国家（地区）的金牌、银牌、铜牌数
example:gold={'中国':38,'美国':34}
饼图的数据类型
'''
def medals2020():
    df1 = pd.read_csv('static/data/medalList.csv', encoding='gbk')[0:6]
    country = df1['Unnamed: 1'].tolist()[:-1]
    gold = df1['Unnamed: 2'].tolist()[:-1]
    silver = df1['Unnamed: 3'].tolist()[:-1]
    copper = df1['Unnamed: 4'].tolist()[:-1]
    print(country)
    return country,gold,silver,copper


'''
功能：获取每届奥运会各个国家奖牌和得分情况
参数：
返回值：各个国家奖牌和得分情况
example:
gold=[
["gold_medal", "Country", "Year"],
[64, "中国", 2008],
[10, "加拿大", 2008],

[32, "中国", 2012],
[8, "加拿大", 2012],]
动态柱形图的数据类型
'''
def medals_by_year():
    score = []      # 关于这个看有无计算公式，若无则暂不实现
    gold = []
    silver = []
    copper = []
    return score,gold,silver,copper


'''
功能：计算和获取热门运动员的参数
参数：name
返回值：
example:
'''
def athletes_heat():
    data_yang =[173, 21, 56,1020]
    data_long = [175, 33, 70,18200]
    data_sha = [164, 23, 50, 1383]
    data_su = [172,32,65,5935]
    data_xu = [181,30,80,5177]
    data_qhc = [150,14,41,2782]
    data_cm =[163,27,55,1513]
    return data_yang,data_long,data_sha,data_su,data_xu,data_qhc,data_cm

'''
功能：统计参赛运动员体重和身高分布（male|female）（散点图）
参数：
返回值：data_year_m, data_year_f, data_year_m, data_year_f
example:统计体重
[
[161.2, 51.6], [167.5, 59.0], [159.5, 49.2], [157.0, 63.0], [155.8, 53.6],
[170.0, 59.0], [159.1, 47.6], [166.0, 69.8], [176.2, 66.8], [160.2, 75.2],
[172.5, 55.2], [170.9, 54.2], [172.9, 62.5], [153.4, 42.0], [160.0, 50.0],
],
'''
def weight_height_distribution():
    athelets = pd.read_csv('./static/data/athlete_events.csv')
    temp = athelets[athelets['Year']>=2000]
    temp = temp[temp['Season'] == 'Summer']
    year_dict = temp.groupby('Year').indices
    Year_table = []#[2000, 2004, 2008, 2012, 2016]
    for keyelem in year_dict:
        Year_table.append(keyelem)
    temp_male = temp[temp['Sex']=='M']
    temp_female = temp[temp['Sex']=='F']
    weight_male, weight_female, height_male, height_female = {},{},{},{}
    for i in Year_table:
        cur_maletable = temp_male[temp_male['Year'] == i]
        cur_femaletable = temp_female[temp_female['Year'] == i]
        #处理缺失值
        weight_male[i] = cur_maletable['Weight'].dropna(axis=0, how='any', inplace=False).to_list()
        weight_female[i] = cur_femaletable['Weight'].dropna(axis=0, how='any', inplace=False).to_list()
        height_male[i] = cur_maletable['Height'].dropna(axis=0, how='any', inplace=False).to_list()
        height_female[i] = cur_femaletable['Height'].dropna(axis=0, how='any', inplace=False).to_list()
    data_2000_f,data_2004_f,data_2008_f,data_2012_f,data_2016_f = [],[],[],[],[]
    data_2000_m,data_2004_m,data_2008_m,data_2012_m,data_2016_m = [],[],[],[],[]

    for h, w in zip(height_male[2000], weight_male[2000]):
        data_2000_m.append([h, w])
    for h, w in zip(height_male[2004], weight_male[2004]):
        data_2004_m.append([h, w])
    for h, w in zip(height_male[2008], weight_male[2008]):
        data_2008_m.append([h, w])
    for h, w in zip(height_male[2012], weight_male[2012]):
        data_2012_m.append([h, w])
    for h, w in zip(height_male[2016], weight_male[2016]):
        data_2016_m.append([h, w])
    for h, w in zip(height_female[2000], weight_female[2000]):
        data_2000_f.append([h, w])
    for h, w in zip(height_female[2004], weight_female[2004]):
        data_2004_f.append([h, w])
    for h, w in zip(height_female[2008], weight_female[2008]):
        data_2008_f.append([h, w])
    for h, w in zip(height_female[2012], weight_female[2012]):
        data_2012_f.append([h, w])
    for h, w in zip(height_female[2016], weight_female[2016]):
        data_2016_f.append([h, w])
    return data_2000_f, data_2004_f, data_2008_f, data_2012_f, data_2016_f, data_2000_m, data_2004_m, data_2008_m, data_2012_m, data_2016_m



'''
功能：统计参赛运动员年龄段分布（male|female）（柱形图）
参数：
返回值：age_male，age_female
example:年龄统计段：
(0, 14]         2
(14, 18]      252
(18, 23]     2707
(23, 28]     3225
(28, 32]     1340
(32, 37]      585
(37, 100]     279
{2000: [2, 252, 2707, 3225, 1340, 585, 279], 2004: [4, 220, 2466, 3028, 1313, 578, 288]}
'''
def age_distribution():
    athelets = pd.read_csv('./static/data/athlete_events.csv')
    temp = athelets[athelets['Year']>=2000]
    temp = temp[temp['Season'] == 'Summer']
    year_dict = temp.groupby('Year').indices
    Year_table = []#[2000, 2004, 2008, 2012, 2016]
    for keyelem in year_dict:
        Year_table.append(keyelem)
    temp_male = temp[temp['Sex']=='M']
    temp_female = temp[temp['Sex']=='F']
    bins = [0,14,18,23,28,32,37,100]
    age_male= {}
    age_female = {}
    for i in Year_table:
        cur_maletable = temp_male[temp_male['Year'] == i]
        cur_femaletable = temp_female[temp_female['Year'] == i]
        male_agelist = pd.value_counts(pd.cut(cur_maletable['Age'],bins)).sort_index().to_list()
        female_agelist = pd.value_counts(pd.cut(cur_femaletable['Age'],bins)).sort_index().to_list()
        age_male[i] = male_agelist
        age_female[i] = female_agelist
    #   根据功能描述返回值为age_male 和 age_female
    age_2000_m=age_male[2000]
    age_2004_m = age_male[2004]
    age_2008_m = age_male[2008]
    age_2012_m = age_male[2012]
    age_2016_m = age_male[2016]
    age_2000_f = age_female[2000]
    age_2004_f = age_female[2004]
    age_2008_f = age_female[2008]
    age_2012_f = age_female[2012]
    age_2016_f = age_female[2016]
    return age_2000_m,age_2004_m,age_2008_m,age_2012_m,age_2016_m,age_2000_f,age_2004_f,age_2008_f,age_2012_f,age_2016_f
'''
功能：统计性别比例
参数：
返回值：男女性别数量字典sex_2020,sex_history
example：sex_2020{'Male':500,'Female':400}
'''
def sex():
    sex_2020={'Male':500,'Female':400}
    sex_history={'Male':5020,'Female':3600}
    return sex_2020,sex_history

'''
功能：活期系统日期
参数：null
返回值：系统日期
example:2021-08-17
'''
def current_datetime():
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)


def base_view(request):
    return render(request,'base.html')

#   index渲染
def index_view(request):
    df = pd.read_csv('static/data/medalList.csv', encoding='gbk')
    medals_2020 = np.array(df)
    wea,date=weather()
    date=str(datetime.datetime.now()).split(' ')[0]
    country, gold, silver, copper = medals2020()
    items=[
        ['https://www.miguvideo.com/mgs/website/prd/sportLive.html?mgdbId=120000168561&channelId=0132_CAAAB000902014800000000&pwId=3d21c7db29cd4911853ecc4b814bd9a3','                        男子10米跳台跳水决赛               2021-08-07  14:00',],
        ['https://www.miguvideo.com/mgs/website/prd/sportLive.html?mgdbId=120000169260&channelId=0132_CAAAB000902014800000000&pwId=3d21c7db29cd4911853ecc4b814bd9a3','                        乒乓球男子团体金牌赛                2021-08-06  18:15',],
        ['https://www.miguvideo.com/mgs/website/prd/sportLive.html?mgdbId=120000169346&channelId=0132_CAAAB000902014800000000&pwId=3d21c7db29cd4911853ecc4b814bd9a3','                        乒乓球女子团体金牌赛                2021-08-06  18:15',],
        ['https://www.miguvideo.com/mgs/website/prd/sportLive.html?mgdbId=120000170462&channelId=0132_CAAAB000902014800000000&pwId=3d21c7db29cd4911853ecc4b814bd9a3','                        排球女子分组预选赛小组赛B组          2021-08-02  15:05',],
        ['https://www.miguvideo.com/mgs/website/prd/sportLive.html?mgdbId=120000176638&channelId=0132_CAAAB000902014800000000&pwId=3d21c7db29cd4911853ecc4b814bd9a3','                        男子争先赛1/32决赛复活赛            2021-08-02  16:31',],
        ['https://www.miguvideo.com/mgs/website/prd/sportLive.html?mgdbId=120000176604&channelId=0132_CAAAB000902014800000000&pwId=3d21c7db29cd4911853ecc4b814bd9a3','                        游泳比赛收官日                     2021-08-01  09:15',],
        ['https://www.miguvideo.com/mgs/website/prd/sportLive.html?mgdbId=120000176539&channelId=0132_CAAAB000902014800000000&pwId=3d21c7db29cd4911853ecc4b814bd9a3','                        游泳男女4X100米混合泳接力           2021-07-31  09:15',],
        ['https://www.miguvideo.com/mgs/website/prd/sportLive.html?mgdbId=120000176538&channelId=0132_CAAAB000902014800000000&pwId=3d21c7db29cd4911853ecc4b814bd9a3','                        田径第2比赛日晚场                   2021-07-31  17:50'],
    ]
    #   locals()    返回当前作用域内的所有变量
    return render(request,'index.html',locals())

#   details渲染
def details_view(request):
    # map
    mapdata = data_on_map()
    mapdata = json.dumps(mapdata)
    # pie_medals
    pie_gold = {}
    for k, v in zip(["中国", "美国", "日本","英国","ROC"], [38, 33, 24,19,17]):
        pie_gold.update({k: v, }, )
    pie_gold = json.dumps(pie_gold)
    pie_silver = {}
    for k, v in zip(["中国", "美国", "日本","英国","ROC"], [29, 36, 12,20,24]):
        pie_silver.update({k: v, }, )
    pie_silver = json.dumps(pie_silver)
    pie_copper = {}
    for k, v in zip(["中国", "美国", "日本","英国","ROC"], [17, 32, 16,21,22]):
        pie_copper.update({k: v, }, )
    # print(pie_copper)
    pie_copper = json.dumps(pie_copper)
    # data = json.dumps(data)
    #   w-h
    data_2000_f, data_2004_f, data_2008_f, data_2012_f, data_2016_f, data_2000_m, data_2004_m, data_2008_m, data_2012_m, data_2016_m=weight_height_distribution()
    #   age
    age_2000_m,age_2004_m,age_2008_m,age_2012_m,age_2016_m,age_2000_f,age_2004_f,age_2008_f,age_2012_f,age_2016_f=age_distribution()
    age_male,age_female=[],[]
    #   sex_pie
    count_2000={'Male':sum(age_2000_m),'Female':sum(age_2000_f)}
    count_2004={'Male':sum(age_2004_m),'Female':sum(age_2004_f)}
    count_2008 = {'Male': sum(age_2008_m), 'Female': sum(age_2008_f)}
    count_2012 = {'Male': sum(age_2012_m), 'Female': sum(age_2012_f)}
    count_2016 = {'Male': sum(age_2016_m), 'Female': sum(age_2016_f)}
    count_2020 = {'Male': 5560, 'Female': 4605}
    #   heat
    heat_yang,heat_long,heat_sha,heat_su,heat_xu,heat_qhc,heat_cm = athletes_heat()

    return render(request,'details.html',locals())

#   news渲染
def news_view(request,category=0):
    print(category)
    news=getnews(category)
    wea, date = weather()
    return render(request,'news.html',{'news':news,'date':date})


#   dynaHistory渲染
def view_dynaHistory(request):
    return render(request,'dynaHistory.html',locals())
